﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gacn.ControleAlunos.Library.Entities;
using Gacn.ControleAlunos.Library.DataAccess;
using System.Data.SqlClient;
using System.Data;

namespace Gacn.ControleAlunos.Library.Business
{
    public class PresencaBiz
    {

        #region Insert Methods
        /// <summary>
        /// Metodo reponsavel por salvar presencas dos alunos
        /// Seu tipo de retorno e boolean porque sua acao e atomica
        ///     no banco de dados. Ou ele salva ou nao salva.
        /// </summary>
        /// <param name="?"></param>
        public static Boolean SalvaPresenca(PresencaEntity presenca)
        {
            //salvapresenca
            return false;
        }

        /// <summary>
        /// Metodo responsavel por salvar presencas dos alunos
        /// Seu tipo de retorno e boolean porque sua acao e atomica,
        ///     nao importando se ele conseguiu salvar uma. Caso qualquer
        ///     uma falhe, a operacao inteira sera cancelada.
        /// </summary>
        /// <param name="?"></param>
        /// <returns></returns>
        public static Boolean SalvaPresenca(List<PresencaEntity> presencas)
        {

            SqlConnection connection = null;
            SqlCommand command = null;

            connection = Util.GetConnection();
            connection.Open();

            command = connection.CreateCommand();
            SqlTransaction transaction;

            // Start a local transaction.
            transaction = connection.BeginTransaction("Salva Presencas");

            // Must assign both transaction object and connection
            // to Command object for a pending local transaction
            command.Connection = connection;
            command.Transaction = transaction;

            try
            {
                foreach (PresencaEntity p in presencas)
                {


                    if (p.Equals(presencas[0]))
                    {
                        command.CommandText = "uspRegistraPresencaPorIdPessoa";
                        command.CommandType = CommandType.StoredProcedure;

                        command.Parameters.Add("idPessoa", SqlDbType.Int).Value = p.PessoaID;
                        command.Parameters.Add("DataAula", SqlDbType.DateTime).Value = p.Data;
                        command.Parameters.Add("idInsertUser", SqlDbType.Int).Value = 2;

                        command.Parameters.Add("SUCESSO", SqlDbType.Bit).Direction = ParameterDirection.Output;
                        command.Parameters.Add("ProcComment", SqlDbType.VarChar, 1000).Direction = ParameterDirection.Output;
                    }
                    else
                    {
                        command.Parameters["idPessoa"].Value = p.PessoaID;
                        command.Parameters["DataAula"].Value = p.Data;
                    }

                    command.ExecuteNonQuery();
                }

                // Attempt to commit the transaction.
                transaction.Commit();
                Console.WriteLine("Both records are written to database.");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
                Console.WriteLine("  Message: {0}", ex.Message);

                // Attempt to roll back the transaction.
                try
                {
                    transaction.Rollback();
                }
                catch (Exception ex2)
                {
                    // This catch block will handle any errors that may have occurred
                    // on the server that would cause the rollback to fail, such as
                    // a closed connection.
                    Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                    Console.WriteLine("  Message: {0}", ex2.Message);
                }

                return false;
            }
        }
        #endregion

        #region Get Methods
        public static List<PresencaEntity> GetAllPresenca()
        {
            List<PresencaEntity> presencas = new List<PresencaEntity>();

            DataTable dt = CursoDataAccess.GetAllCursoEntity();

            foreach (DataRow row in dt.Rows)
                presencas.Add(new PresencaEntity(
                   int.Parse(row["idPessoa"].ToString()),
                   DateTime.Parse(row["dtHrPresenca"].ToString())
                 )
             );

            return presencas;
        }

        public static List<PresencaDetalhadaEntity> GetAllPresencaDetalhada()
        {
            List<PresencaDetalhadaEntity> presencas = new List<PresencaDetalhadaEntity>();
            DataTable dt = CursoDataAccess.GetAllCursoEntity();

            foreach (DataRow row in dt.Rows)
            {
                PresencaDetalhadaEntity p = new PresencaDetalhadaEntity();

                p.PessoaID = int.Parse(row["idPessoa"].ToString());
                p.Data = DateTime.Parse(row["dtHrPresenca"].ToString());

                p.Aluno = AlunoBiz.GetAlunoDetalhadoPorAlunoID(p.PessoaID);

                presencas.Add(p);
            }

            return presencas;
        }


        #endregion

        #region Update Methods
        public static bool AtualizaDataDaPresenca(PresencaDetalhadaEntity a)
        {
            PresencaDataAccess.AtualizaDataDaPresenca(a.ID, a.Data);
            return false;
        }
        #endregion


    }
}
